#!/usr/bin/env python
# coding:utf-8
'''
DMZAvatar统计
'''
import os,sys,common.db
from logging import *
from common.date_time import *

def Goods1(strCurDay):
    log(INFO,'StatDay : '+ strCurDay)
    strDay = strCurDay.replace('-','')
    

    delete_sql='delete from statisticdb.DMZGoodsTimeDay where Date="%s"'%(strDay)
    cur.execute(delete_sql)
    cnn.commit()
    
    sql='''
insert into statisticdb.DMZGoodsTimeDay (Date,ZoneID,GoodsID,
    Count_7,Money_7,GameCoin_7,
    Count_30,Money_30,GameCoin_30,
    Count_Forever,Money_Forever,GameCoin_Forever)
select '%s',ZoneID,GoodsID,
    count(if(Quantity=604800,1,null)),    sum(if(Quantity=604800 && PayMeans=2,Price,0)),    sum(if(Quantity=604800 && PayMeans=1,Price,0)),
    count(if(Quantity=2592000,1,null)),   sum(if(Quantity=2592000 && PayMeans=2,Price,0)),   sum(if(Quantity=2592000 && PayMeans=1,Price,0)),
    count(if(Quantity=0x7fffffff,1,null)),sum(if(Quantity=0x7fffffff && PayMeans=2,Price,0)),sum(if(Quantity=0x7fffffff && PayMeans=1,Price,0))
from dmz_bill_%s.goods_detail
where UseMeans=1 and Quantity in (604800,2592000,0x7fffffff)
group by ZoneID,GoodsID'''%(strDay,strDay);

    try:
        count = cur.execute(sql)
    except Exception,data:
        log(ERROR,data)
        sys.exit(0)
        
    cnn.commit()
                    

if __name__ != "__main__":

    cnn = common.db.connect('billDB')
    cur = cnn.cursor()

    if len(sys.argv) > 3:
        strBeginDay = sys.argv[2]
        strEndDay = sys.argv[3]
        if len(strBeginDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        if len(strEndDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        for strCurDay in intervalDay(strBeginDay,strEndDay):
            Goods1(strCurDay)
    elif len(sys.argv) > 2:
        strCurDay = sys.argv[2]
        if len(strCurDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        Goods1(strCurDay)
    else:
        strCurDay = GetDay(-1) ##"2010-01-14"
        Goods1(strCurDay)

    cur.close()
    cnn.close()

